package me.shiqiang.im.consumer;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import me.shiqiang.im.msg.Resp;
import me.shiqiang.im.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @author cuishiqiang
 * @date 2017/12/16 上午11:15
 */
@Component("P2pMsgConsumer")
public class P2pMsgConsumer implements MessageListener {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    SocketIOServer server;

    @Override
    public Action consume(Message message, ConsumeContext context) {
        String s = new String(message.getBody());
        try {
            logger.info("接收消息: {}", s);
            String cmd = message.getKey();
            String cId = message.getShardingKey();
            server.getAllClients();

            SocketIOClient client = server.getClient(UUID.fromString(cId));
            if (client != null) {
                Resp resp = JsonUtils.getInstance().fromJson(s, Resp.class);
                client.sendEvent(cmd, resp);
            } else {
                logger.info("{}未连接connection，msg:{}", cId, s);
            }
            return Action.CommitMessage;
        } catch (Exception e) {
            logger.error("发送消息到客户端出现异常", e);
            return Action.ReconsumeLater;
        }
    }
}
